package com.study.sxc.service;

import com.study.sxc.Dao.IUsageDao;
import com.study.sxc.Entity.Usage;
import com.study.sxc.service.machineService;
import com.study.sxc.service.machineTypeService;
import com.study.sxc.Entity.Machine;
import com.study.sxc.Entity.MachineType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Service
public class usageService {

    private static final Logger log = LoggerFactory.getLogger(usageService.class);

    @Resource
    IUsageDao usageDao;

    @Resource
    private machineService machineService;
    @Resource
    private machineTypeService machineTypeService;

    public List<Usage> getUsages(List<Integer> ids) {
        log.info("查询使用记录列表，参数：{}", ids);
        List<Usage> usages = usageDao.getUsages(ids);
        log.info("DAO层返回数据：{}", usages);
        if(usages == null || usages.isEmpty()) {
            return new ArrayList<>();
        }
        return usages;
    }

    public int addUsage(Usage usage) {
        log.info("新增使用记录，参数：{}", usage);
        // 插入前自动设置startTime为当前时间
        usage.setStartTime(new java.util.Date());
        int result = usageDao.addUsage(usage);
        log.info("新增使用记录结果：{}", result);
        return result;
    }

    public int updateUsage(Usage usage) {
        log.info("更新使用记录，参数：{}", usage);
        // 下机时自动设置endTime为当前时间
        usage.setEndTime(new java.util.Date());
        // 计算时长（分钟），并赋值给duration
        if (usage.getStartTime() != null && usage.getEndTime() != null) {
            long diffMillis = usage.getEndTime().getTime() - usage.getStartTime().getTime();
            int minutes = (int) (diffMillis / (60 * 1000));
            usage.setDuration(minutes);
        }
        // 设置支付状态为已支付
        usage.setPaymentStatus("paid"); // 设置为'paid'
        // 计算费用cost
        // 1. 通过machineId获取Machine对象
        Machine machine = machineService.getMachineById(usage.getMachineId());
        if (machine != null) {
            // 2. 获取typeId
            Integer typeId = machine.getTypeId();
            // 3. 通过typeId获取MachineType对象
            MachineType machineType = machineTypeService.getMachineTypeById(typeId);
            if (machineType != null) {
                // 4. 获取hourlyRate
                BigDecimal hourlyRate = machineType.getHourlyRate();
                // 5. 计算费用（按小时计费，duration为分钟）
                if (hourlyRate != null && usage.getDuration() != null) {
                    BigDecimal hours = new BigDecimal(usage.getDuration()).divide(new BigDecimal(60), 2, RoundingMode.HALF_UP);
                    BigDecimal cost = hourlyRate.multiply(hours);
                    usage.setCost(cost);
                }
            }
        }
        int result = usageDao.updateUsage(usage);
        log.info("更新使用记录结果：{}", result);
        return result;
    }

    public int deleteUsage(Integer id) {
        log.info("删除使用记录，参数：{}", id);
        int result = usageDao.deleteUsage(id);
        log.info("删除使用记录结果：{}", result);
        return result;
    }

    public Usage getUsageById(Integer id) {
        return usageDao.getUsageById(id);
    }

    /**
     * 查询所有上机记录
     */
    public java.util.List<com.study.sxc.Entity.Usage> getAllUsages() {
        return usageDao.getAllUsages();
    }
} 